package com.tangyuan.live.util;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.tangyuan.common.util.OkHttpUtils;
import com.tangyuan.live.entity.dto.GroupCustomMsgDto;
import com.tangyuan.model.User;
import com.tangyuan.model.live.LiveRoom;
import com.tencentyun.TLSSigAPIv2;
import lombok.extern.slf4j.Slf4j;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import cn.hutool.json.JSONArray;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.*;

@Component
@Slf4j
public class IMUtil {

    private final static long expire = 60*60*24*365;

    @Value("${im.secretKey:}")
    String secretKey;
    @Value("${im.imAppid:}")
    Long imAppid;
    @Value("${im.adminAccount:}")
    String adminAccount;

    private String identifier = "";

    //计算UserSig
    public String generateUserSig(String userId){
        TLSSigAPIv2 api = new TLSSigAPIv2(imAppid,secretKey);
        return api.genSig(userId, expire);
    }
    //随机32为无符号整数
    public long generateUnsignedInt() {
        return new Random().nextInt() & 0xffffffffL;
    }

    private String joinTencentCloudUrl(String portUrl,String url){
        if(StrUtil.isEmpty(identifier)){
            identifier = generateUserSig(adminAccount);
        }
        return "https://console.tim.qq.com/v4/"+portUrl+"/"+url+"?sdkappid="+imAppid+"&identifier="+adminAccount+"&usersig="+identifier+"&random="+generateUnsignedInt()+"&contenttype=json";
    }

    //创建群组
    public String createGroup(LiveRoom room){
        String url = joinTencentCloudUrl("group_open_http_svc","create_group");
        JSONObject object = new JSONObject();
        object.set("Owner_Account",room.getUserId().toString());
        object.set("Type","AVChatRoom");
        object.set("Name",room.getRoomName());
        return requestTencentCloud(url, object.toString());
    }

    //解散群组
    public String destroyGroup(String group){
        String url = joinTencentCloudUrl("group_open_http_svc","destroy_group");
        JSONObject object = new JSONObject();
        object.set("GroupId",group);
        return requestTencentCloud(url, object.toString());
    }

    //创建IM用户
    public String createIMUser(User user) {
        String url = joinTencentCloudUrl("im_open_login_svc","account_import");
        JSONObject object = new JSONObject();
        object.set("UserID",user.getId().toString());
        object.set("Nick",user.getName());
        object.set("FaceUrl",user.getHeadImage());
        return requestTencentCloud(url, object.toString());
    }

    //添加群成员
    public String addGroupMember(String groupId, List<String> userIds) {
        String url = joinTencentCloudUrl("group_open_http_svc","add_group_member");
        JSONObject object = new JSONObject();
        // 设置 GroupId
        object.set("GroupId", groupId);

        // 构建 MemberList
        JSONArray memberList = new JSONArray();
        for (String userId : userIds) {
            JSONObject member = new JSONObject();
            member.set("Member_Account", userId);
            memberList.add(member);
        }
        // 设置 MemberList
        object.set("MemberList", memberList);
        return requestTencentCloud(url, object.toString());
    }

    //发送群组消息
    public String sendGroupMsg(String groupId,Long userId,String message) {
        String url = joinTencentCloudUrl("group_open_http_svc","send_group_msg");

        GroupCustomMsgDto.MsgBodyDto bodyDto = new GroupCustomMsgDto.MsgBodyDto();
        bodyDto.setMsgType("TIMCustomElem");
        bodyDto.setMsgContent(new JSONObject().set("customMsg", message));

        GroupCustomMsgDto msgDto = new GroupCustomMsgDto();
        msgDto.setRandom(generateUnsignedInt());
        msgDto.setGroupId(groupId);
        msgDto.setMsgPriority("High");
        msgDto.setFrom_Account(userId.toString());
        msgDto.setMsgBody(Collections.singletonList(bodyDto));
        return requestTencentCloud(url, JSONUtil.toJsonStr(msgDto));
    }

    //获取在线人数
    public Long getOnLineNumber(String groupId) {
        String url = joinTencentCloudUrl("group_open_http_svc","get_online_member_num");
        JSONObject object = new JSONObject();
        object.set("GroupId",groupId);
        String number = requestTencentCloud(url, object.toString());
        return StrUtil.isEmpty(number) ? 0L: Long.parseLong(new org.json.JSONObject(number).get("OnlineMemberNum").toString());
    }


    //移出成员
    public String shiftOutUser(String groupId, List<String> userIds) {
        String url = joinTencentCloudUrl("group_open_http_svc","ban_group_member");
        JSONObject object = new JSONObject();
        object.set("GroupId",groupId);
        object.set("Members_Account",userIds);
        object.set("Duration",60*60*24);
        return requestTencentCloud(url, object.toString());
    }

    //禁言用户
    public void shutUpUser(String groupId, List<String> userIds,Integer muteTime) {
        if(CollectionUtils.isEmpty(userIds)){
            return;
        }
        String url = joinTencentCloudUrl("group_open_http_svc","forbid_send_msg");
        JSONObject object = new JSONObject();
        object.set("GroupId",groupId);
        object.set("Members_Account",userIds);
        object.set("MuteTime",muteTime);
        //单条请求限制禁言用户数量
        int restrict = 500;
        //需请求次数
        int number = (userIds.size() / restrict);
        //如果超过限制
        if(userIds.size() > restrict){
            int i;
            for (i = 0; i < number; i++) {
                object.set("Members_Account",userIds.subList(i * restrict,i * restrict +restrict));
                requestTencentCloud(url, object.toString());
                //如果是最后一次请求 并且请求数量是限制的整倍数 则返回最后一次请求
                if(i == number - 1 && userIds.size() % restrict == 0){
                    return;
                }
            }
            object.set("Members_Account",userIds.subList(i * restrict,userIds.size()));
        }else {
            object.set("Members_Account",userIds);
        }
        requestTencentCloud(url, object.toString());
    }

    //请求腾讯云
    public String requestTencentCloud(String url,String json){
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, json);
        Request request = new Request.Builder()
                .url(url)
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .build();
        String bodyResponse = "";
        try {
            Response response = OkHttpUtils.getInstance().newCall(request).execute();
            bodyResponse = response.body().string();
            if(new JSONObject(bodyResponse).get("ActionStatus").equals("FAIL")){
                log.error("调用腾讯云返回异常结果,Url{},参数:{},返回结果:{}",url,json,bodyResponse);
                return "";
            }
        }catch (Exception e){
            log.error("请求失败:url:{},参数:{},异常:{}",url,json,e.toString());
            return "";
        }
        return bodyResponse;
    }



}
